<script lang="ts" setup>
import { reactive, ref, watch } from 'vue';
import { Form, message } from 'ant-design-vue';
import { getCfgAtteItemApi, putCfgAtteApi } from '@/common/apis/attendance';
import dayjs from 'dayjs'; // 引入 dayjs 用于时间格式化
import type { WorkingType } from '@/common/types/attendance-type'


const useForm = Form.useForm;

const labelCol = { span: 4 };
const wrapperCol = { span: 14 };
// 获取工作时间数据
const workingHours = ref()

const modelRef = reactive<WorkingType>({
    morning: [], // 上午上班时间  
    afternoon: []  // 下午上班时间
});

const rulesRef = reactive({
    departmentId: [
        {
            required: true,
            message: '请选择部门',
        },
    ],
    morning: [
        {
            required: true,
            message: '请选择上午上班时间！',
        },
    ],
    afternoon: [
        {
            required: true,
            message: '请选择下午出勤时间！',
        },
        // 新增自定义校验规则
        {
            validator: (rule: any, value: string[]) => {
                if (value && modelRef.morning) {
                    // 直接比较字符串
                    if (value < modelRef.morning) {
                        return Promise.reject('下午出勤时间不能早于早上出勤时间'); // 验证失败
                    }
                }
                return Promise.resolve(); // 验证成功
            },
        }
    ]
});

const props = defineProps({
    closeModel: {
        type: Function,
        request: true
    },
    departmentId: {
        type: Number,
        request: true
    }
})


const { resetFields, validate, validateInfos } = useForm(modelRef, rulesRef);

// 将时间字符串转换为 dayjs 对象
const parseTimeString = (timeString: string) => {
    console.log(timeString, 'timeString')
    return dayjs(`2025-03-20 ${timeString}`); // 使用固定日期，仅用于时间格式化
};

// 根据部门id查询考勤设置
const getCfgAtteItemData = async () => {
    const res = await getCfgAtteItemApi({ departmentId: props.departmentId });
    console.log(res)
    workingHours.value = res.data.data;
    console.log('后端返回的数据:', workingHours.value);

    // 将后端返回的时间字符串转换为 dayjs 对象并赋值给 modelRef
    if (workingHours.value) {
        modelRef.morning = [
            parseTimeString(workingHours.value.morningStartTime),
            parseTimeString(workingHours.value.morningEndTime)
        ];
        modelRef.afternoon = [
            parseTimeString(workingHours.value.afternoonStartTime),
            parseTimeString(workingHours.value.afternoonEndTime)
        ];
    }
};


// 点击保存
const onSubmit = () => {
    validate()
        .then(async () => {
            // 转换 morning 和 afternoon 时间范围
            const requestData = {
                departmentId: props.departmentId,
                morningStartTime: modelRef.morning[0].format('HH:mm'), // 转换为字符串格式
                morningEndTime: modelRef.morning[1].format('HH:mm'),
                afternoonStartTime: modelRef.afternoon[0].format('HH:mm'),
                afternoonEndTime: modelRef.afternoon[1].format('HH:mm')
            };

            // 更改上班时间
            await putCfgAtteApi(requestData)
            // 刷新数据
            await getCfgAtteItemData()
            // 关闭弹窗
            if (props.closeModel) {
                props.closeModel();
            }
            message.success('更新成功')
        })
        .catch(err => {
            console.log('error', err);
        });
};


// 监听 departmentId 的变化
watch(
    () => props.departmentId, // 监听 props.departmentId
    (newVal) => {
        if (newVal) {
            console.log('departmentId 发生变化:', newVal);
            getCfgAtteItemData(); // 重新获取数据
        }
    },
    { immediate: true } // 立即执行一次
);

</script>

<template>
    <a-form :label-col="labelCol" :wrapper-col="wrapperCol">
        <!-- 早上工作时间 -->
        <a-form-item label="早上工作：" v-bind="validateInfos.morning">
            <a-time-range-picker v-model:value="modelRef.morning" />
        </a-form-item>
        <!-- 下午工作时间 -->
        <a-form-item label="下午工作：" v-bind="validateInfos.afternoon">
            <a-time-range-picker format="HH:mm" v-model:value="modelRef.afternoon" />
        </a-form-item>
        <!-- 确定按钮 -->
        <a-form-item :wrapper-col="{ span: 14, offset: 4 }">
            <a-button type="primary" @click.prevent="onSubmit">保存更新</a-button>
            <a-button style="margin-left: 10px" @click="resetFields">取消</a-button>
        </a-form-item>
    </a-form>
</template>


<style scoped>
.error-infos :deep(.ant-form-explain) {
    white-space: pre-line;
}
</style>